package com.ede.roverhu.simplebackstage.Activities;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.ede.roverhu.simplebackstage.Domain.CharDes;
import com.ede.roverhu.simplebackstage.Domain.GattInfo;
import com.ede.roverhu.simplebackstage.R;
import com.ede.roverhu.simplebackstage.Utils.LogUtils;
import com.junkchen.blelib.BleService;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class BlueToothInfoActivity extends BaseActivity {
    final public static int SERVICE_BIND = 0x00;
    final public static int SERVICE_NOTFOUND = 0x01;
    final public static int LINEARLAYOUT_ADDSERVICE = 0x02;
    private List<GattInfo> gattlist;

    private BleService mBleService;
    private ListView mlistview;
    private boolean mIsBind;
    private String mac = "";
    private String title = "";
    private TextView mtextView;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == SERVICE_BIND)
                LogUtils.e("服务已经开启");
            if (msg.what == SERVICE_NOTFOUND)
                LogUtils.e("服务未发现");
            if (msg.what == LINEARLAYOUT_ADDSERVICE) {
                mlistview.setAdapter(new BluetoothInfoAdapter(gattlist));
            }
        }
    };
    //绑定Service
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mBleService = ((BleService.LocalBinder) iBinder).getService();
            if (mBleService != null) {
                mHandler.sendEmptyMessage(SERVICE_BIND);
            } else {
                mHandler.sendEmptyMessage(SERVICE_NOTFOUND);
            }
            if (mBleService.initialize()) {
                if (mBleService.enableBluetooth(true)) {
                    LogUtils.e("蓝牙已开启");
                    BleConnect();
                }
            } else {
                LogUtils.e("蓝牙不支持");
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            LogUtils.e("连接失败");
            mBleService = null;
            mIsBind = false;
        }
    };


    private void doBindService() {
        Intent serviceIntent = new Intent(this, BleService.class);
        if (bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE)) {
            LogUtils.e("绑定成功");
        } else {
            LogUtils.e("绑定失败");
        }

    }

    private void doUnBindService() {
        if (mIsBind) {
            unbindService(serviceConnection);
            mBleService = null;
            mIsBind = false;
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blue_tooth_info);
        mac = getIntent().getStringExtra("ibeacon");
        title = getIntent().getStringExtra("title");
        getSupportActionBar().setTitle(title);
        mlistview = (ListView) findViewById(R.id.listview);
        doBindService();
    }

    private void BleConnect() {
        mBleService.connect(mac);
        mBleService.setOnConnectListener(new OnConnectListener());
        mBleService.setOnServicesDiscoveredListener(new OnServicesDiscoveredListener());
        mBleService.setOnDataAvailableListener(new BleService.OnDataAvailableListener() {
            @Override
            public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                LogUtils.e("==========Read==========");
                LogUtils.e("characteristic==>" + characteristic.getUuid().toString());
                LogUtils.e("byteArrLen======>" + characteristic.getValue().length);
                LogUtils.e("========================");
            }

            @Override
            public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                try {
                    LogUtils.e("===========Write========");
                    LogUtils.e("characteristic==>" + characteristic.getUuid().toString());
                    LogUtils.e("value============>" + new String(characteristic.getValue(), "UTF-8"));
                    LogUtils.e("========================");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
                try {
                    LogUtils.e("==========Read==========");
                    LogUtils.e("descriptor======>" + descriptor.getUuid().toString());
                    LogUtils.e("value===========>" + new String(descriptor.getValue(), "UTF-8"));
                    LogUtils.e("========================");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        doUnBindService();
    }

    private class OnConnectListener implements BleService.OnConnectionStateChangeListener {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                LogUtils.e("Ble连接已断开");
            } else if (newState == BluetoothProfile.STATE_CONNECTING) {
                LogUtils.e("Ble正在连接");
            } else if (newState == BluetoothProfile.STATE_CONNECTED) {
                LogUtils.e("Ble已连接");
            } else if (newState == BluetoothProfile.STATE_DISCONNECTING) {
                LogUtils.e("Ble正在断开连接");
            }
        }
    }

    private class OnServicesDiscoveredListener implements BleService.OnServicesDiscoveredListener {
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            List<BluetoothGattService> list = gatt.getServices();
            gattlist = new ArrayList<>();
            for (final BluetoothGattService bgs : list) {
                GattInfo gattInfo = new GattInfo();
                LogUtils.e("Service================>" + bgs.getUuid().toString());
                gattInfo.service = bgs.getUuid().toString();
                ArrayList<CharDes> mlist = new ArrayList<>();
                for (BluetoothGattCharacteristic characteristic : bgs.getCharacteristics()) {
                    CharDes charDes = new CharDes();
                    LogUtils.e("characteristic=====>" + characteristic.getUuid());
                    charDes.Characteristic = characteristic.getUuid();
                    for (BluetoothGattDescriptor des : characteristic.getDescriptors()) {
                        LogUtils.e("Descriptor========>" + des.getUuid().toString());
                        charDes.des = des.getUuid().toString();
                    }
                    mlist.add(charDes);
                }
                gattInfo.mlist = mlist;
                gattlist.add(gattInfo);
            }
            mHandler.sendEmptyMessage(LINEARLAYOUT_ADDSERVICE);

        }
    }

    private class BluetoothInfoAdapter extends BaseAdapter {

        private List<GattInfo> list;
        private LayoutInflater mInflator;
        private int serviceNum;
        private int[] b;

        public BluetoothInfoAdapter(List<GattInfo> list) {
            this.list = list;
            mInflator = getLayoutInflater();
            serviceNum = list.size();
            b = new int[serviceNum];
            for (int xNum = 0; xNum < serviceNum; xNum++) {
                b[xNum] = 1 + list.get(xNum).mlist.size();
                if (xNum > 0) {
                    b[xNum] = b[xNum] + b[xNum - 1];
                }
                LogUtils.e("b[" + xNum + "]" + b[xNum]);
            }
        }

        @Override
        public int getCount() {
            int count = 0;
            for (GattInfo g : list) {
                count = count + g.mlist.size();
            }
            return count + list.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder = null;
            int temp = 0;
            for (; temp < b.length; temp++) {
                if (i < b[temp])
                    break;
            }
            LogUtils.e("index:" + i);
            LogUtils.e("b[temp]:" + b[temp]);
            LogUtils.e("temp:" + temp);


            if (view == null) {
                if (temp == 0) {
                    if (i == 0) {
                        view = mInflator.inflate(R.layout.item_bluetooth_service, null);
                        viewHolder = new ViewHolder();
                        viewHolder.serviceName = (TextView) view.findViewById(R.id.tv_service);
                        view.setTag(viewHolder);
                    } else {
                        view = mInflator.inflate(R.layout.item_bluetooth_characteristic, null);
                        viewHolder = new ViewHolder();
                        viewHolder.des = (TextView) view.findViewById(R.id.tv_des);
                        viewHolder.characteristic = (TextView) view.findViewById(R.id.tv_char);
                        viewHolder.info = (EditText) view.findViewById(R.id.et_info);
                        viewHolder.submit = (Button) view.findViewById(R.id.bt_submit);
                        view.setTag(viewHolder);
                    }
                } else {
                    if (i - b[temp - 1] == 0) {
                        view = mInflator.inflate(R.layout.item_bluetooth_service, null);
                        viewHolder = new ViewHolder();
                        viewHolder.serviceName = (TextView) view.findViewById(R.id.tv_service);
                        view.setTag(viewHolder);
                    } else {
                        view = mInflator.inflate(R.layout.item_bluetooth_characteristic, null);
                        viewHolder = new ViewHolder();
                        viewHolder.des = (TextView) view.findViewById(R.id.tv_des);
                        viewHolder.characteristic = (TextView) view.findViewById(R.id.tv_char);
                        viewHolder.info = (EditText) view.findViewById(R.id.et_info);
                        viewHolder.submit = (Button) view.findViewById(R.id.bt_submit);
                        view.setTag(viewHolder);
                    }
                }
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }


            if (temp == 0) {
                if (i == 0) {
                    if (viewHolder.serviceName == null) {
                        view = mInflator.inflate(R.layout.item_bluetooth_service, null);
                        viewHolder = new ViewHolder();
                        viewHolder.serviceName = (TextView) view.findViewById(R.id.tv_service);
                        view.setTag(viewHolder);
                    }
                    viewHolder.serviceName.setText("service:" + list.get(temp).service);
                } else {
                    if (viewHolder.characteristic == null) {
                        view = mInflator.inflate(R.layout.item_bluetooth_characteristic, null);
                        viewHolder = new ViewHolder();
                        viewHolder.des = (TextView) view.findViewById(R.id.tv_des);
                        viewHolder.characteristic = (TextView) view.findViewById(R.id.tv_char);
                        viewHolder.info = (EditText) view.findViewById(R.id.et_info);
                        viewHolder.submit = (Button) view.findViewById(R.id.bt_submit);
                        view.setTag(viewHolder);
                    }
                    viewHolder.characteristic.setText(list.get(temp).mlist.get(i - 1).Characteristic + "");
                    viewHolder.des.setText(list.get(temp).mlist.get(i - 1).des + "");
                }
            } else {
                if (i - b[temp - 1] == 0) {
                    if (viewHolder.serviceName == null) {
                        view = mInflator.inflate(R.layout.item_bluetooth_service, null);
                        viewHolder = new ViewHolder();
                        viewHolder.serviceName = (TextView) view.findViewById(R.id.tv_service);
                        view.setTag(viewHolder);
                    }
                    viewHolder.serviceName.setText("service:" + list.get(temp).service);
                } else {
                    if (viewHolder.characteristic == null) {
                        view = mInflator.inflate(R.layout.item_bluetooth_characteristic, null);
                        viewHolder = new ViewHolder();
                        viewHolder.des = (TextView) view.findViewById(R.id.tv_des);
                        viewHolder.characteristic = (TextView) view.findViewById(R.id.tv_char);
                        viewHolder.info = (EditText) view.findViewById(R.id.et_info);
                        viewHolder.submit = (Button) view.findViewById(R.id.bt_submit);
                        view.setTag(viewHolder);
                    }
                    //LogUtils.e("listIndex" + (i - b[temp - 1]));
                    viewHolder.characteristic.setText(list.get(temp).mlist.get(i - b[temp - 1] - 1).Characteristic + "");
                    viewHolder.des.setText(list.get(temp).mlist.get(i - b[temp - 1] - 1).des + "");
                }
            }
            return view;
        }

        class ViewHolder {
            TextView serviceName;
            TextView des;
            TextView characteristic;
            EditText info;
            Button submit;
        }

    }
}
